package com.laundry.importer;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;

import com.laundry.lib.Database;
import com.laundry.lib.MachineDateAvailability;

public class Importer {

	
	public int populateMachineSlotAvaialabilty(Date date){
		int numberOfRows=0;				
		java.sql.Date sqlDate= new java.sql.Date(Date.parse(date.toGMTString()));
		String insertQuery=		" insert into laundry_machineslotavailabilty select machine.machineid, slot.id,machine.date,0 from laundry_machines machine "+
		"join laundry_timeslotsmasterlist slot "+
		"where machine.isAvailabe=1 and machine.date='"+ sqlDate.toString() +"'";
		String dateCheckQuery=" select count(*) from laundry_machineslotavailabilty where  date =' "+sqlDate.toString()+"'";
		Connection conn=null;
		try {
		 conn= Database.getConnection();
		
		Statement st=conn.createStatement();
		ResultSet result=st.executeQuery(dateCheckQuery);
		
		result.next();
		int numberOfExistingEntries= result.getInt(1);	    
		result.close();
		conn.close();
		
		if(numberOfExistingEntries == 0){
			conn=Database.getConnection();
			st=conn.createStatement();
			numberOfRows= st.executeUpdate(insertQuery);			
		}		
		}
		catch(Exception ex){
			System.out.println(" Error " );			
		}
		finally{
			
		}
		
		return numberOfRows;
	}
	public String PopulateMachines(ArrayList<MachineDateAvailability> machines){
		int rows=-1;
		String insert = "insert into laundry_machines values ";
		for(MachineDateAvailability machine : machines){
			int isAvailable=machine.isAvailable()?1:0;
			insert+=" ( "+machine.getMachineId()+",'"+new java.sql.Date(Date.parse(machine.getDate().toGMTString()))+
						"' , "+isAvailable+",'"+machine.getRemarks()+"'),";
		}
		insert= insert.substring(0,insert.length()-1);
		insert+=" ";
		try{
		Connection connection=Database.getConnection();
		Statement statement=connection.createStatement();
		rows= statement.executeUpdate(insert);
		}
		catch(Exception ex){
			ex.printStackTrace();
		}				
		return insert + rows; 
	}
	
	
}
